package com.tubang.organization.controller;


import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.tubang.common.constant.Constants;
import com.tubang.common.util.GsonQuick;
import com.tubang.common.util.MsgCode;
import com.tubang.common.util.ResultData;
import com.tubang.common.util.StringUtils;
import com.tubang.component.entity.CompanyEntity;
import com.tubang.component.entity.UserEntity;
import com.tubang.component.service.ICompanyService;
import com.tubang.component.service.IUserService;
import com.tubang.component.util.RequestUtil;

/**
 * <p>
 * 组织表 部门人员 前端控制器
 * </p>
 *
 * @author maxl
 * @since 2017-11-30
 */
@RestController
@RequestMapping("/companyUser")
public class CompanyUserController {
	private Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private IUserService userService;

    @Resource
	private ICompanyService companyService;
    
    /**
     * 获取部门员工
     * @return
     */
    @GetMapping(value = "getUserByCompanyId")
    public ResultData getUserByCompanyId(@RequestParam(required = true) String companyId,
										 @RequestParam(required = false) String comId,
										 @RequestParam(required = false) String realName,
                                         @RequestParam(required = false, defaultValue = "1") Integer page,
                                         @RequestParam(required = false, defaultValue = "10") Integer rows) {
        try {
			EntityWrapper<CompanyEntity> companyEntityWrapper = new EntityWrapper<CompanyEntity>();
			companyEntityWrapper.eq("parent_id",companyId);
			companyEntityWrapper.eq("enable", Constants.DEFAULT_VAULE_ONE);
			List<CompanyEntity> companyEntities = companyService.selectList(companyEntityWrapper);
			List<String> companyIds=new ArrayList<String>();
			for (CompanyEntity companyEntity : companyEntities) {
				companyIds.add(companyEntity.getId());
			}
			companyIds.add(companyId);
			List<UserEntity> userEntities = userService.selectPageByCompanyId(new Page<UserEntity>(page, rows), companyIds,comId,realName);
			EntityWrapper<UserEntity> userEntityWrapper = new EntityWrapper<UserEntity>();
			if(StringUtils.isNotEmpty(comId)){
				userEntityWrapper.eq("company_id",comId);
			}else{
				userEntityWrapper.in("company_id",companyIds);
			}
			userEntityWrapper.eq("enable", Constants.DEFAULT_VAULE_ONE);
			if(StringUtils.isNoneEmpty(realName)){
				userEntityWrapper.like("real_name",realName);
			}
			int count = userService.selectCount(userEntityWrapper);
			return ResultData.result(true).setData(userEntities).setTotalCount(count);
        } catch (Exception e) {
        	e.printStackTrace();
			logger.error("[getUserByCompanyId]==> method[getUserByCompanyId],错误原因：[{}]", e.getMessage());
            return ResultData.result(false);
        }
    }



    /**
     * 获取部门员工详情
     *
     * @return
     */
    @GetMapping(value = "getUserByCompanyInfo")
    public ResultData getUserByCompanyInfo(@RequestParam(required = true) String userId) {
        try {
            UserEntity userEntity = userService.selectById(userId);
            return ResultData.result(true).setData(userEntity);
        } catch (Exception e) {
        	e.printStackTrace();
			logger.error("[getUserByCompanyInfo]==> method[getUserByCompanyInfo],错误原因：[{}]", e.getMessage());
            return ResultData.result(false).setMsg(MsgCode.DEFAULT_ERROR_MSG);
        }
    }



    /**
     * 组织 添加员工
     *
     * @return
     */
	@PostMapping(value = "insertOrUpdateCompanyUserEntity")
	public ResultData insertOrUpdateCompanyUserEntity(HttpServletRequest request) {
		try {


			String receivePostJson = RequestUtil.receivePostJson(request);
			UserEntity userEntity = GsonQuick.toObject(receivePostJson, UserEntity.class);
			Timestamp now = new Timestamp(System.currentTimeMillis());
//			String id = userEntity.getId();
//			if (StringUtils.isBlank(id)) {
//				userEntity.setCreateTime(now);
//			}
			userEntity.setUpdateTime(now);
			userService.insertOrUpdate(userEntity);
			return ResultData.result(true).setData(userEntity);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("[insertOrUpdateCompanyUserEntity]==> method[insertOrUpdateCompanyUserEntity],错误原因：[{}]", e.getMessage());
			return ResultData.result(false);
		}
	}

    /**
     * 删除部门用户
     * @return
     */
	@GetMapping(value = "deleteCompanyUserEntity")
	public ResultData deleteCompanyUserEntity(@RequestParam String id) {
		try {
			UserEntity userEntity = userService.selectById(id);
			if (userEntity == null) {
				return ResultData.result(false).setCode(MsgCode.ADDRESS_FAIL_IS_NOT_EXIST).setMsg(MsgCode.ADDRESS_FAIL_IS_NOT_EXIST_DESC);
			}
			// 更新状态
			userEntity.setEnable(Boolean.FALSE);
			userService.updateById(userEntity);
			return ResultData.result(true);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("[deleteCompanyUserEntity]==> method[deleteCompanyUserEntity],错误原因：[{}]", e.getMessage());
			return ResultData.result(false);
		}
	}

}
